package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserLoginService;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserLoginService {
    @Override
    public ResponseResult login(LoginDto dto) {
        if(dto.getEquipmentId() == null && (StringUtils.isEmpty(dto.getPhone())&&StringUtils.isEmpty(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断账号密码是否为空
        if (StringUtils.isEmpty(dto.getPhone())|| StringUtils.isEmpty(dto.getPassword())){
            //3.设备登录
            if(dto.getEquipmentId() == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }else {
            //查询该账号是否存在
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,dto.getPhone());
            List<ApUser> list = list(wrapper);
            if (list!=null && list.size()==1){
                ApUser apUser = list.get(0);
                String password = dto.getPassword();
                String pwdSalt= password+apUser.getSalt();
                String newPwd = DigestUtils.md5DigestAsHex(pwdSalt.getBytes());
                //判断密码是否正确
                if (apUser.getPassword().equals(newPwd)) {
                    Map<String, Object> map = new HashMap<>();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    map.put("user",apUser);
                    //返回token
                    return ResponseResult.okResult(map);
                }else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        }
    }
}
